package com.web.cloud.controller.pub;

import com.web.cloud.exception.BusinessException;
import com.web.cloud.viewmodel.pub.JsonResponse;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by liuhaiming on 2016-05-29.
 */
public abstract class BasicController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public BasicController() {
    }

    @ExceptionHandler
    @ResponseBody
    public Object handleException(HttpServletRequest request, Exception ex) {
        Throwable rootCause = ExceptionUtils.getRootCause(ex);
        Object handleEx = rootCause != null?rootCause:ex;
        if(handleEx instanceof BusinessException) {
            String code = ((BusinessException)handleEx).getCode();
            this.logger.warn(code + ": " + ((Throwable)handleEx).getMessage());
        } else {
            this.logger.error(((Throwable)handleEx).getMessage(), (Throwable)handleEx);
        }

        return this.error((Throwable)handleEx);
    }

    protected <T> JsonResponse<T> success() {
        return this.success((T)null);
    }

    protected <T> JsonResponse<T> success(T data) {
        return JsonResponse.success(data);
    }

    protected <T> JsonResponse<T> error(Throwable e) {
        return JsonResponse.error(e);
    }

    protected <T> JsonResponse<T> error(String code) {
        return JsonResponse.error(code);
    }

    protected <T> JsonResponse<T> error(String code, Object[] args) {
        return JsonResponse.error(code, args);
    }

    protected <T> JsonResponse<T> error(String code, String message) {
        return JsonResponse.error(code, message);
    }

    protected <T> JsonResponse<T> error(String code, String message, T data) {
        return JsonResponse.error(code, message, data);
    }
}
